package cn.edu.swu.miniwebsvr.core;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private final Config config = Config.getInstance();
    private final ExecutorService threadPool = Executors.newFixedThreadPool(10);

    public void start(){
        //  [222024321072041/王耀东] 实现 ServerSocket 的创建和监听
        try(ServerSocket serverSocket = new ServerSocket(config.getPort())) {
            System.out.println("MiniWebSvr 启动成功，监听端口：" + config.getPort());

            while (true) {
                Socket clientSocket = serverSocket.accept();
                System.out.println("接收到客户端连接: " + clientSocket.getInetAddress()+":"+clientSocket.getPort());
                threadPool.execute(new RequestProfessor(clientSocket));
            }
        } catch (IOException e){
            System.err.println("服务器启动失败或运行异常: " + e.getMessage());
            threadPool.shutdown();
        }
    }

    private static class RequestProfessor implements  Runnable{
        private final Socket socket;
        public RequestProfessor(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            // 完善请求处理流程，确保异常安全和资源关闭
            try {
                Parameter request = HttpParser.parse(socket.getInputStream());
                Router router = new Router();
                router.route(request,socket.getOutputStream());

            } catch (Exception e) {
                // [222024321072041/王耀东] 文件读取异常，返回 500 Internal Server Error
                sendInternalServerError(socket);
            }finally {
                try {
                    if (socket != null) socket.close();
                } catch (IOException e) { /* ignore */ }
            }
        }
        private void sendInternalServerError(Socket socket) {
            try {
            OutputStream output = socket.getOutputStream();
            PrintWriter writer = new PrintWriter(output);

            String errorContent = "<!DOCTYPE html>\n" +
                    "<html lang=\"zh-CN\">\n" +
                    "<head>\n" +
                    "    <meta charset=\"UTF-8\">\n" +
                    "    <title>500 Internal Server Error - MiniWebSvr</title>\n" +
                    "</head>\n" +
                    "<body>\n" +
                    "    <div class=\"container\">\n" +
                    "        <h1>🚨 500 Internal Server Error</h1>\n" +
                    "        <p>服务器在处理请求时发生内部错误。</p>\n" +
                    "        <div class=\"student-info\">\n" +
                    "            [2021111111/张三] - MiniWebSvr\n" +
                    "        </div>\n" +
                    "    </div>\n" +
                    "</body>\n" +
                    "</html>";

            byte[] contentBytes = errorContent.getBytes(StandardCharsets.UTF_8);

            writer.println("HTTP/1.1 500 Internal Server Error");
            writer.println("Content-Type: text/html; charset=UTF-8");
            writer.println("Content-Length: " + contentBytes.length);
            writer.println("Connection: close");
            writer.println("Server: MiniWebSvr/1.0");
            writer.println();
            writer.flush();

            output.write(contentBytes);
            output.flush();

        } catch (IOException e) {
            System.err.println("发送500错误页面时发生异常: " + e.getMessage());
        }
    }
    }
}
